package edu.szte.ovrt.datahandler.ini;

import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;

import edu.szte.ovrt.datahandler.core.AbstractDocumentReader;
import edu.szte.ovrt.datahandler.core.DocumentReaderException;
import edu.szte.ovrt.datahandler.model.Document;
import edu.szte.ovrt.datahandler.model.Section;

public class INIReader extends AbstractDocumentReader {

	public INIReader(final Reader reader) {
		super(reader);
	}

	@Override
	public Document readDocument() throws DocumentReaderException {
		final Document retDoc = new Document();

		try {
			String line;
			Section section = null;
			// read document
			while ((line = m_reader.readLine()) != null) {

				if (!line.contains(" = ") && line.matches("\\[.*\\]")) {
					// start a new section
					section = retDoc.newSection(line.trim().subSequence(1, line.trim().length() - 1).toString());

				} else if (section != null && line.contains(" = ")) {
					// this line is an item -> scan it
					final Scanner lineScanner = new Scanner(line);
					lineScanner.useDelimiter(" = ");
					section.newItem(lineScanner.next().trim(), lineScanner.next().trim());
				} else {
					// if something isn't proper
					throw new DocumentReaderException("The file isn't a proper ini file!");
				}
			}
		} catch (final IOException e) {
			throw new DocumentReaderException(e);
		}

		return retDoc;
	}

}
